package ltd.newbee.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.dao.MallUserAddressMapper;
import ltd.newbee.mall.dao.NewBeeMallOrderMapper;
import ltd.newbee.mall.entity.NewBeeMallOrder;
import ltd.newbee.mall.entity.RouteQueryReqDto;
import ltd.newbee.mall.entity.SfCommonRequest;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import ltd.newbee.mall.util.SfApiUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 顺丰路由查询服务
 */
@Service
@Slf4j
public class SfRouteQueryService {


    @Value("${sf.PARTNER_ID}")
    private String PARTNER_ID;

    @Value("${sf.CHECK_WORD}")
    private String CHECK_WORD;

    @Value("${sf.API_URL}")
    private String API_URL;

    @Autowired
    private NewBeeMallOrderMapper newBeeMallOrderMapper;




  /*  private static final String PARTNER_ID = "YYACSARC";
    private static final String CHECK_WORD = "ETSizRkUXRabVdLVCyh2h67z0BjQSese";
    private static final String API_URL = "https://sfapi-sbox.sf-express.com/std/service";*/

    //private static final String API_URL = "https://sfapi-sbox.sf-express.com/std/service";


    private static final String SERVICE_CODE = "EXP_RECE_SEARCH_ROUTES";

    /**
     * 查询路由信息
     *
     * @param trackingType    查询号类别: 1-运单号 2-客户订单号
     * @param trackingNumbers 查询号列表
     * @param language        语言
     * @param methodType      路由查询类别: 1-标准路由查询 2-定制路由查询
     * @return 路由响应数据
     */
    public JSONObject queryRoutes(Integer trackingType, List<String> trackingNumbers,
                                  String language, Integer methodType, String checkPhoneNo) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            // === 1. 参数校验 ===
            if (trackingType == null) {
                throw new IllegalArgumentException("trackingType不能为空");
            }
            if (trackingNumbers == null || trackingNumbers.isEmpty()) {
                throw new IllegalArgumentException("trackingNumber不能为空");
            }
            if (trackingNumbers.size() > 10) {
                throw new IllegalArgumentException("单次查询最多支持10个单号");
            }

            // === 2. 构建业务数据 ===
            RouteQueryReqDto msgDataDto = new RouteQueryReqDto();
            msgDataDto.setTrackingType(trackingType);
            msgDataDto.setTrackingNumber(trackingNumbers);
            msgDataDto.setLanguage(language != null ? language : "zh-CN");
            msgDataDto.setMethodType(methodType != null ? methodType : 1);
            msgDataDto.setCheckPhoneNo(checkPhoneNo);

            String msgDataJson = SfApiUtil.toJsonString(msgDataDto);
            log.info("业务数据报文(msgData): " + msgDataJson);

            // === 3. 生成时间戳和请求ID ===
            long timestamp = System.currentTimeMillis();
            String requestId = SfApiUtil.generateRequestId();

            // === 4. 生成数字签名 ===
            String msgDigest = SfApiUtil.generateMsgDigest(msgDataJson, timestamp, CHECK_WORD);

            // === 5. 构建form表单参数 ===
            List<NameValuePair> formParams = new ArrayList<>();
            formParams.add(new BasicNameValuePair("partnerID", PARTNER_ID));
            formParams.add(new BasicNameValuePair("requestID", requestId));
            formParams.add(new BasicNameValuePair("serviceCode", SERVICE_CODE));
            formParams.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
            formParams.add(new BasicNameValuePair("msgDigest", msgDigest));
            formParams.add(new BasicNameValuePair("msgData", msgDataJson));


            // accessToken为null，使用数字签名认证

            log.info("form表单参数:");
            for (NameValuePair param : formParams) {
                log.info("  " + param.getName() + "=" + param.getValue());
            }

            // === 6. 发送HTTP请求（form表单格式）===
            HttpPost httpPost = new HttpPost(API_URL);
            // 正确设置Content-Type为application/x-www-form-urlencoded
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8));

            log.info("发送请求到: " + API_URL);
            response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            log.info("HTTP状态码: " + statusCode);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                log.info("响应结果: " + responseStr);
                return JSONObject.parseObject(responseStr);
            } else {
                throw new RuntimeException("响应内容为空");
            }

        } catch (Exception e) {
            log.error("调用顺丰路由查询API失败", e);
            throw new RuntimeException("调用顺丰路由查询API失败: " + e.getMessage(), e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("关闭HTTP连接失败", e);
            }
        }
    }


    /**
     * 单个运单号查询
     */
    public Result queryRouteByWaybill(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder == null) {
            return ResultGenerator.genFailResult("没有订单信息");
        }
        //验证是否是当前userId下的订单，否则报错
        if (!userId.equals(newBeeMallOrder.getUserId())) {
            return ResultGenerator.genFailResult(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
        }
        JSONObject responseData = queryRoutes(1, Arrays.asList(newBeeMallOrder.getTrackingNo()), "zh-CN", 1, newBeeMallOrder.getSendPhone());

        if(!"A1000".equals(responseData.get("apiResultCode"))){
            return ResultGenerator.genFailResult("没有物流信息");
        }
        log.info("responseData=" + JSONObject.toJSONString(responseData.get("apiResultData")));
        return ResultGenerator.genSuccessResult(responseData.getJSONObject("apiResultData"));
    }

}
